import { PayloadAction, createSlice } from '@reduxjs/toolkit';
import { persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';

export interface MenuItem {
    key: string;
    label: string;
    path?: string;
    children?: MenuItem[];
}

interface GlobalState {
    dynamicRouter: string[]; // 动态路由
    collapsed: boolean; // 菜单缩放
    selectedKeys: string[]; // 当前所选菜单
    openKeys: string[]; // 当前展开菜单
}

const initialState: GlobalState = {
    dynamicRouter: [],
    collapsed: false,
    selectedKeys: [],
    openKeys: [],
};

export const globalSlice = createSlice({
    name: 'global',
    initialState: initialState,
    reducers: {
        updateDynamicRouter(state, action: PayloadAction<string[]>) {
            state.dynamicRouter = action.payload;
        },
        updateCollapsed(state, action: PayloadAction<boolean>) {
            state.collapsed = action.payload;
        },
        updateOpenKeys(state, action: PayloadAction<string[]>) {
            state.openKeys = action.payload;
        },
        updateSelectedKeys(state, action: PayloadAction<string[]>) {
            state.selectedKeys = action.payload;
        },
    },
});

// 配置 redux-persist 的持久化选项
const persistConfig = {
    key: 'global', // 存储在 localStorage 中的键名
    storage, // 使用 localStorage 作为存储介质
    whitelist: ['collapsed', 'selectedKeys', 'openKeys'], // 指定需要持久化的 reducer 键名
};

export const { updateDynamicRouter, updateCollapsed, updateOpenKeys, updateSelectedKeys } =
    globalSlice.actions;

// export default globalSlice.reducer;
export default persistReducer(persistConfig, globalSlice.reducer);
